// userModel.js
//实现与MySql交互
var mysql = require('mysql');
var $conf = require('../../config/db');
var $util = require('../../util/util');
var $util_string = require('../../util/string');
var $sql = require('./userSqlMapping');

//使用连接池，提升性能
var pool = mysql.createPool($util.extend({}, $conf.mysql));

//向前台返回JSON方法的简单封装
var jsonWrite = function(res, ret){
	if (typeof ret === 'undefined') {
		res.json({
			code : '1',
			msg: '操作失败'
		});
	} else {
		res.json( ret );
	}
}

module.exports = {
	add : function(req, res, callback){
		pool.getConnection(function(err, connection){
			//获取前台页面传过来的参数
			// var param = req.query || req.params;
			//post接收，数据加密、验证数据
			var post_data = req.body.user
		 	var username = post_data.username;
		 	var password = post_data.password;
		 	//md5加密密码
		 	md5_passwd = $util_string.md5(password);
			//建立连接，向表中插入数据
			connection.query($sql.insert, [username, md5_passwd], function(err, result){
				if ( result ) {
					result = {
						code:200,
						msg:'增加成功',
						data: result,
					}
				}else{
					result = {
						code:0,
						msg:'增加失败',
					}
				}

				//释放连接
				connection.release();
				//能过回调函数返回到前台
				callback(err, result);

			})
		})
	},
	delete:function(req,res,next){
		pool.getConnection(function(err, connection){
			var id =+ req.query.id;
			connection.query($sql.delete, id, function(err, result){
				if (result.affectedRows > 0 ) {
					result = {
						code : 200,
						msg : '删除成功'
					};
				}else{
					result = void 0;
				}
				jsonWrite(res, result);
				connection.release();
			})
		})
	}
}

